package fr.teuteuf.runstickmanrun;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.Array;

public class Animation {
	
	private Array<Frame> arrayFrames;
	private int indexCurrentFrame;
	private float animTime;
	private float totalDuration;
	private boolean looping;
	
	public Animation(boolean looping) {
		arrayFrames = new Array<Frame>();
		totalDuration = 0;
		this.looping = looping;
		start();
	}
	
	public Animation() {
		this(true);
	}
	
	public void start() {
		animTime = 0;
		indexCurrentFrame = 0;
	}
	
	public void addFrame(Texture texture, int x, int y, int width, int height, float duration) {
		totalDuration += duration;
		arrayFrames.add(new Frame(new TextureRegion(texture, x, y, width, height), totalDuration));
	}
	
	public void update(float elapsedTime) {
		if(arrayFrames.size > 1 && !(looping && animTime >= totalDuration)) {
			animTime += elapsedTime;
			
			if (animTime >= totalDuration) {
				if(looping) {
					animTime = animTime % totalDuration;
					indexCurrentFrame = 0;
				} else {
					animTime = totalDuration;
				}
			}
			
			while(animTime > arrayFrames.get(indexCurrentFrame).endTime) {
				indexCurrentFrame++;
			}
		}
	}
	
	public TextureRegion getCurrentFrameTexture() {
		return arrayFrames.get(indexCurrentFrame).textureRegion;
	}
	
	private class Frame {
		TextureRegion textureRegion;
		float endTime;
		
		public Frame(TextureRegion textureRegion, float endTime) {
			this.textureRegion = textureRegion;
			this.endTime = endTime;
		}
	}
}
